import '@/page/Login/index.scss'
import { useState, useEffect, useRef } from 'react'
import { LockOutlined, UserOutlined, SendOutlined } from '@ant-design/icons'
import { Button, Form, Input, Flex } from 'antd'
import { loginService, registerService } from '@/api/user'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'
import { useToken } from '@/context/tokenContext'
import { useUserInfo } from '@/context/userInfoContext'

function Login() {
  const navigate = useNavigate()
  const [isLogin, setIsLogin] = useState(true)
  // 创建表单实例，使用Form组件提供的useForm函数创建，需要绑定到表单
  const [form] = Form.useForm()
  const onFinish = values => {
    console.log('拿到的表单数据: ', values)
  }
  // 表单验证规则
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 1, max: 10, message: '请输入长度为1-10的字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 12, message: '请输入6-12位密码', trigger: 'blur' }
    ],
    rePassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator(_, value) {
          const passwordValue = form.getFieldValue('password')
          if (value && passwordValue && value !== passwordValue) {
            return Promise.reject(new Error('两次输入密码不一致'))
          }
          return Promise.resolve()
        },
        trigger: 'blur'
      }
    ],
    email: [
      { required: true, message: '请输入邮箱号', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        message: '请输入正确的邮箱号',
        trigger: 'blur'
      }
    ]
  }
  const formRef = useRef()
  useEffect(() => {
    formRef.current = form
  }, [form])
  useEffect(() => {
    formRef.current.resetFields()
  }, [isLogin])
  const { storeToken } = useToken()
  const { setUserInfo } = useUserInfo()
  // 登录逻辑
  const handleLogin = async () => {
    try {
      const res = await loginService(form.getFieldValue())
      console.log('登录res :', res.data)
      storeToken(res.data.data.token)
      setUserInfo(res.data.data.userInfo)
      message.success('登录成功')
      // 跳转首页
      navigate('/')
    } catch (error) {
      console.log('登录失败:', error)
      message.error('登录失败')
    }
  }
  // 注册逻辑
  const handleRegister = async () => {
    try {
      const res = await registerService(form.getFieldValue())
      console.log('注册res :', res.data)
      if(res.data.code === 200) {
        message.success('注册成功')
        // 切换登陆状态
        setIsLogin(true)
      } else {
        message.error(res.data.message)
        return
      }
    } catch (error) {
      console.log('注册失败:', error)
      message.error('注册失败')
    }
  }
  // 重置密码逻辑

  return (
    <div className="login-index">
      <div className="login-left">
        <div className={'form-container'}>
          {/* 登录页 */}
          <Form
            name="login"
            form={form}
            initialValues={{ remember: true }}
            style={{ maxWidth: 360, display: isLogin ? 'block' : 'none' }}
            onFinish={onFinish}
          >
            <Form.Item>
              <h1>用户登录</h1>
            </Form.Item>
            <Form.Item
              name="username"
              rules={rules.username}
            >
              <Input style={{ height: '2.5rem' }} prefix={<UserOutlined />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={rules.password}
            >
              <Input style={{ height: '2.5rem' }} prefix={<LockOutlined />} type="password" placeholder="密码" />
            </Form.Item>
            <Form.Item>
              <Flex justify="space-between" align="center">
                <a onClick={() => setIsLogin(false)}>去注册</a>
                <a href="">忘记密码？</a>
              </Flex>
            </Form.Item>
            <Form.Item>
              <Button onClick={handleLogin} className="login-button" block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
          {/* 注册页 */}
          <Form
            name="register"
            form={form}
            initialValues={{ remember: true }}
            style={{ maxWidth: 360, display: !isLogin ? 'block' : 'none' }}
            onFinish={onFinish}
          >
            <Form.Item>
              <h1>用户注册</h1>
            </Form.Item>
            <Form.Item
              name="username"
              rules={rules.username}
            >
              <Input style={{ height: '2.5rem' }} prefix={<UserOutlined />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={rules.password}
            >
              <Input style={{ height: '2.5rem' }} prefix={<LockOutlined />} type="password" placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="rePassword"
              dependencies={['password']}
              rules={rules.rePassword}
            >
              <Input style={{ height: '2.5rem' }} prefix={<LockOutlined />} type="password" placeholder="确认密码" />
            </Form.Item>
            <Form.Item
              name="email"
              rules={rules.email}
            >
              <Input style={{ height: '2.5rem' }} prefix={<SendOutlined />} type="email" placeholder="邮箱号" />
            </Form.Item>
            <Form.Item>
              <Flex justify="space-between" align="center">
                <a onClick={() => setIsLogin(true)}>去登录</a>
              </Flex>
            </Form.Item>
            <Form.Item>
              <Button onClick={handleRegister} className="login-button" block type="primary" htmlType="submit">
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>

      <div className="login-right">
        <div className="decoration-circle"></div>
        <div className="decoration-circle-2"></div>
        <h2>欢迎回来</h2>
        <p>请登录您的账户继续访问</p>
      </div>
    </div>
  )
}

export default Login